//
//  StockMonitorService.m
//  Stock
//
//  Created by blacksun on 11-7-7.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "StockMonitorService.h"


@implementation StockMonitorService

-(void)querySTAT{
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@dig/fund?id=STAT",kHostName];
    NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockMonitorServiceQuerySTAT,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [urlStr release];
}
-(void)queryStockWithType:(NSString *)type{
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@dig/fund?id=%@",kHostName,type];
    NSLog(@"%@",urlStr);
    NSURL *url = [[NSURL alloc] initWithString:urlStr]; 
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    request.delegate = self;
    request.userInfo = [NSDictionary dictionaryWithObjectsAndKeys:kStockMonitorServiceQueryStockWithType,kASIHttpRequestUserinfoKey,nil];
    [request startAsynchronous];
    [self.workingRequests addObject:request];
    [request release];
    [url release];
    [urlStr release];
}


#pragma mark -delegate callback
- (void)requestFinished:(ASIHTTPRequest *)request{
    NSDictionary *userinfo = request.userInfo;
    CommonUtil *commonUtil = [CommonUtil shareInstance];
    NSString *action = [userinfo objectForKey:kASIHttpRequestUserinfoKey];
    NSMutableArray *result = [NSMutableArray array];
    if ([kStockMonitorServiceQuerySTAT isEqualToString:action]) {
        NSString *responseString = [request responseString];
        NSArray *stockDicts = [[responseString JSONValue] objectForKey:@"stocks"];
        for (NSDictionary *stockDict in stockDicts) {
            StockMonitor *stockMonitor = [[StockMonitor alloc] init];
            [commonUtil copyMapEntries:stockDict toObject:stockMonitor];
            [result addObject:stockMonitor];
            [stockMonitor release];
        }
        [self.delegate requestFinishedWithResult:result andUserinfo:userinfo];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"request error");
    [self.delegate requestFinishedwithError:request.error andUserinfo:request.userInfo];
}
@end
